﻿using System;
using System.Collections.Generic;
using System.Xml;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YArchitech.Controls;
using YArchitech.LIB;
using YArchitech.Revit;

namespace YArchitech.HVAC.AuxiliaryCurve
{
	internal class AuxiliaryCurveDefine
	{
		public AuxiliaryCurveDefine(ExternalCommandData cmdData)
		{
			this.m_cmdData = cmdData;
			this.m_doc = this.m_cmdData.Application.ActiveUIDocument.Document;
		}

		public void Define()
		{
			Selection selection = this.m_cmdData.Application.ActiveUIDocument.Selection;
			HYModelLineFilter hymodelLineFilter = new HYModelLineFilter();
			IList<Element> list = selection.PickElementsByRectangle(hymodelLineFilter, "请框选要改变为辅助线的模型线……");
			ICollection<ElementId> collection = new List<ElementId>();
			if (list.Count > 0)
			{
				foreach (Element element in list)
				{
					ModelLine line = element as ModelLine;
					ElementId item = null;
					string text = this.DefineDetailLine(line, "boostLineInfo", ref item);
					if (!string.IsNullOrEmpty(text))
					{
						YJKMessageBox.Show(text);
					}
					collection.Add(item);
				}
			}
			YJKRevitTools.SetDetailLineView(collection, this.m_cmdData);
		}

		public string DefineDetailLine(ModelLine line, string alGuid, ref ElementId elemId)
		{
			if (line == null)
			{
				return "没有选中模型线！";
			}
			Curve geometryCurve = line.GeometryCurve;
			DetailLine detailLine = this.m_doc.Create.NewDetailCurve(this.m_doc.ActiveView, geometryCurve) as DetailLine;
			if (detailLine == null)
			{
				return "定义辅助线没有成功！";
			}
			this.m_doc.DeleteElement(line);
			elemId = detailLine.Id;
			this.SaveElementId(elemId, alGuid);
			return "";
		}

		private void SaveElementId(ElementId elemId, string alGuid)
		{
			try
			{
				XmlDocument xmlDocument = new XmlDocument();
				xmlDocument.Load(this.pathName);
				XmlNode xmlNode = xmlDocument.SelectSingleNode("ListDetailLine");
				XmlElement xmlElement = xmlDocument.CreateElement("DetailLine");
				xmlElement.InnerText = elemId.ToString();
				xmlElement.SetAttribute("dlType", alGuid);
				xmlNode.AppendChild(xmlElement);
				xmlDocument.Save(this.pathName);
			}
			catch (Exception)
			{
				throw;
			}
		}

		private string pathName = Product.InstallLocation + "\\Data\\HYSprinklerCheck.XML";

		private ExternalCommandData m_cmdData;

		private Document m_doc;
	}
}
